import React, { createContext } from 'react';
import classnames from 'classnames';
import { MenuItemProps } from './MenuItem';

import MenuItem from './MenuItem';
import SubMenu from './SubMenu';

type MenuMode = 'horizontal' | 'vertical';
type SelectCallback = (selectIndex: string) => void;

/**
 * 定义 Menu 组件的 props 结构类型
 */
export interface MenuProps {
  defaultIndex?: string;
  className?: string;
  mode?: MenuMode;
  style?: React.CSSProperties;
  onSelect?: SelectCallback;
  defaultOpenSubMenus?: string[];
}

/**
 * 定义 Menu 组件的 context 结构类型
 */
interface IMenuContext {
  index: string;
  onSelect?: SelectCallback;
  mode?: MenuMode;
  defaultOpenSubMenus?: string[];
}

/**
 * 扩展 Menu 组件的类型
 */
interface MenuInterface extends React.FC<MenuProps> {
  MenuItem: typeof MenuItem;
  SubMenu: typeof SubMenu;
}

export const MenuContext = createContext<IMenuContext>({ index: '0' });

const Menu: MenuInterface = props => {
  const {
    className,
    mode,
    style,
    children,
    defaultIndex,
    onSelect,
    defaultOpenSubMenus,
  } = props;

  const [currentActive, setActive] = React.useState(defaultIndex);

  const classes = classnames('menu', className, {
    'menu-vertical': mode === 'vertical',
    'menu-horizontal': mode !== 'vertical',
  });

  const handleClick = (index: string) => {
    setActive(index);
    if (onSelect) {
      onSelect(index);
    }
  };

  const passedContext: IMenuContext = {
    index: currentActive ? currentActive : '0',
    onSelect: handleClick,
    mode,
    defaultOpenSubMenus,
  };

  const renderChildren = () => {
    return React.Children.map(children, (child, index) => {
      const childElement = child as React.FunctionComponentElement<
        MenuItemProps
      >;
      const { displayName } = childElement.type;
      if (displayName === 'MenuItem' || displayName === 'SubMenu') {
        return React.cloneElement(childElement, {
          index: index.toString(),
        });
      } else {
        console.error(
          'Warning:Menu has a child which is not a MenuItem component '
        );
      }
    });
  };

  return (
    <ul className={classes} style={style} data-testid='test-menu'>
      <MenuContext.Provider value={passedContext}>
        {renderChildren()}
      </MenuContext.Provider>
    </ul>
  );
};

Menu.defaultProps = {
  defaultIndex: '0',
  mode: 'horizontal',
  defaultOpenSubMenus: [],
};

Menu.SubMenu = SubMenu;
Menu.MenuItem = MenuItem;

export default Menu;
